import tkinter
from tkinter import filedialog
from tkinter import messagebox
import threading
import socket
import time
import os
import configparser as cp
import base64
class A:
    def __init__(self,root):
        self.udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_client.bind(('', 8081))
        self.address = ('169.254.247.196', 8080)
        root.title('sss')
        root.geometry('400x500')
        self.s = tkinter.StringVar()
        self.s_1 = tkinter.Scrollbar(root)
        self.s_1.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self.T = tkinter.Text(root, width=50,yscrollcommand=self.s_1.set)
        self.T.place(x=20, y=20)
        self.T_2 = tkinter.Text(root, width=36, heigh=5)
        self.T_2.place(x=20, y=400)
        self.B = tkinter.Button(root, text='发送', command=self.send)
        self.B.place(x=295, y=400, width=80, heigh=35)
        self.B = tkinter.Button(root, text='保存聊天记录', command=self.save)
        self.B.place(x=295, y=440, width=80, heigh=35)
        self.B = tkinter.Button(root, text='撤回', command=self.withdraw)
        self.B.place(x=295, y=360, width=80, heigh=35)
        self.s_1.config(command=self.T.yview)
        self.filename = ".\config.ini"
        self.i = cp.ConfigParser()
        self.i.read(self.filename, 'utf-8')
        self.start = 1.0
        self.start2 = 1.0
        self.l = []
        self.l2 = []


    def withdraw(self):
        mess = 'withdraw_last_message'
        mess = mess.encode('utf-8')
        a = self.l[0] - 1
        if mess:
            self.udp_client.sendto(base64.b64encode(mess), self.address)
            self.T.delete(a,self.l[1])
            self.T.insert(self.l[0], '你撤回了一条信息\n','tag')
            self.l.pop()
            self.l.pop()


    def save(self):
        mess = self.T.get('0.0','end')
        o = os.path.expanduser(r'C:\Users\Administrator\Desktop')
        file = filedialog.asksaveasfilename(title='选择文件',filetypes=[('文本','txt')],
                                            initialfile='udp聊天记录',initialdir=o)
        if file:
            file += '.txt'
            try:
                with open(file, 'r', encoding='utf-8')as book:
                    m = book.read()
                if m:
                    t = tkinter.messagebox.askyesno(title='注意',message='文件已存在，确定覆盖吗')
                    if t:
                        with open(file,'w',encoding='utf-8') as book:
                            book.write(mess)
                            tkinter.messagebox.showinfo(message='保存成功')
            except:
                with open(file, 'w', encoding='utf-8') as book:
                    book.write(mess)
                    tkinter.messagebox.showinfo(title='保存成功')

    def send(self):
        while True:
            mess = self.T_2.get('0.0', 'end')
            if mess == '\n':
                tkinter.messagebox.showerror(message='不能发送空白')
                break
            else:
                self.udp_client.sendto(str(mess).encode('utf-8'),self.address)
                t = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                self.T.insert('end', t + ' 我:'+'\n''%s' % mess,'tag')
                self.T.tag_add('tag','end')
                self.T.tag_config('tag', foreground=self.i.get('FONT_COLOR', 'other'))
                self.T_2.delete('0.0', 'end')
                self.l.clear()
                g = mess[-2]
                g2 = mess
                app.jisuan_3(g2)
                app.jisuan(g)
                break

    def getIndex(self,pos):
        return tuple(map(int, str.split(self.T.index(pos), ".")))

    def jisuan_3(self,g2):
        pos = self.T.search(g2, self.start, stopindex="end")
        b = app.getIndex(pos)
        r = float(b[0])
        self.l.append(r)

    def jisuan(self,g):
        while True:
            pos = self.T.search(g, self.start, stopindex="end")
            if not pos:
                app.jisuan_2(b)
                break
            b = app.getIndex(pos)
            self.start = pos + "+1c"

    def jisuan_2(self,b):
        r = int(b[0])
        t = int(b[1])
        while True:
            if t > 25:
                t -= 25
                r += 1
            else:
                break
        t += 1
        d = str(r) + '.' + str(t)
        self.l.append(d)
        print(self.l)


    def recv(self):
        while True:
            data = self.udp_client.recvfrom(1024)
            t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            d = data[0].decode('utf-8')
            if d == 'd2l0aGRyYXdfbGFzdF9tZXNzYWdl':
                r = base64.b64decode(d)
                a = self.l2[0] - 1
                self.T.delete(a, self.l2[1])
                self.T.insert(self.l2[0], '你撤回了一条信息\n', 'tag')
                self.l2.pop()
                self.l2.pop()

            else:
                self.T.insert('end', t2 + ' 对方:' + '\n''%s' % data[0].decode('utf-8'), 'a')
                self.T.tag_add('a','end')
                self.T.tag_config('a', foreground=self.i.get('FONT_COLOR', 'myself'))
                self.l2.clear()
                mess = data[0].decode('utf-8')
                g = mess[-2]
                g2 = mess
                app.jisuan_4(g2)
                app.jisuan_6(g)

    def jisuan_4(self,g2):
        pos = self.T.search(g2, self.start2, stopindex="end")
        b = app.getIndex(pos)
        r = float(b[0])
        self.l2.append(r)

    def jisuan_6(self,g):
        while True:
            pos = self.T.search(g, self.start, stopindex="end")
            if not pos:
                app.jisuan_5(b)
                break
            b = app.getIndex(pos)
            self.start = pos + "+1c"

    def jisuan_5(self,b):
        r = int(b[0])
        t = int(b[1])
        while True:
            if t > 25:
                t -= 25
                r += 1
            else:
                break
        t += 1
        d = str(r) + '.' + str(t)
        self.l2.append(d)
        print('2222222:',self.l2)





    def main(self):
        t2 = threading.Thread(target=self.recv)
        t2.start()

if __name__ == '__main__':
    root = tkinter.Tk()
    app = A(root)
    app.main()
    root.mainloop()